﻿module Sustainalytics.Insights {

    import Common = Sustainalytics.Common;
    import LRTM = Sustainalytics.LRTM;

    // InsightsViewController controller
    export class InsightsViewController {
        public insight: InsightDto;
        private $routeParams: any;

        //Ctor.
        constructor(
            private $rootScope: ng.IScope,
            private $scope: ng.IScope,
            private $window: ng.IWindowService,
            private RoutingService: Routing.IRoutingService,
            private $q: ng.IQService,
            private $sce: ng.ISCEService,
            private $location: ng.ILocationService,
            private InsightsService: InsightsService,
            private LongRunningTaskManagerService: LRTM.LongRunningTaskManagerService,
            private notificationFactory: Common.INotificationFactory) {

            var ctx = this;
            ctx.$routeParams = ctx.RoutingService.getRouteParams();
            var insightId: string = ctx.$routeParams['id'];
            var loadInsightPromise = ctx.loadInsight(insightId);
                
            $scope['insightView'] = ctx;
        }

        private loadInsight(id: string): ng.IPromise<InsightDto> {

            var ctx = this;
            var getPromise: ng.IPromise<InsightDto> = ctx.InsightsService.getInsight(id);
            getPromise.then((insight: InsightDto) => {
                ctx.insight = insight;
            });
            return getPromise;
        }

        public DownloadInsightReportLRTM(fileId: string, fileName: string)
        {
            var ctx = this;
            var taskNumber = 201;
            var data = { fileId: fileId + "_" + fileName, fileName: fileName };
            var promise = ctx.LongRunningTaskManagerService.runTask(fileName + "_" + moment().format("DD-MM-YYYY"), JSON.stringify(data), taskNumber, true, null);
        }

        public DownloadInsightReport(url: string) {
            var ctx = this;            
            ctx.$window.location.href = url;
        }


        public RenderHTML(htmlCode: string) {
            var ctx = this;
            return ctx.$sce.trustAsHtml(htmlCode); 
        }

    }


    // register controller 
    angular.module('Sustainalytics.Insights').controller('InsightsViewController',
        ['$rootScope', '$scope', '$window', 'RoutingService', '$q', '$sce', '$location', 'InsightsService', 'LongRunningTaskManagerService', 'notificationFactory', InsightsViewController]);
}
